import { postMyChangepassword, postMySendchangepasswordcode } from "@/api/siderBar/my"
import { useUserStore } from "@/stores"
import { message } from "ant-design-vue"

type FormState = {
    password?: string
    password2?: string
    code?: string
}
export function useEditPassword() {
    const userStore = useUserStore()
    const { state: showPassword, on: openPassword, off: closePassword } = useSwitch(false)
    const {
        clearValidate,
        formLoading,
        formRef,
        formState,
        rules,
        handleFormSubmit,
        resetFormState
    } = useFormState<FormState>({
        getInitialState() {
            return {}
        },
        rules: {
            ...getPasswordRules(() => formState.value, () => formRef.value),
            code: [
                { required: true, message: '请输入验证码' }
            ]
        }
    })
    useEffectScope(() => {
        watch(showPassword, () => {
            if (showPassword.value === false) {
                clearValidate()
                resetFormState()
            }
        })
    })
    async function handleSubmit() {
        // @ts-ignore
        await handleFormSubmit(({ code, password }) => postMyChangepassword({ code, newPassword: password }))
        closePassword()
        message.success("重置密码成功")
        userStore.invalidate()
        toLogin()
    }
    async function triggerSend() {
        await postMySendchangepasswordcode()
        message.success('验证码发送成功')
    }
    return {
        formLoading,
        formState,
        rules,
        showPassword,
        openPassword,
        handleSubmit,
        formRef,
        triggerSend
    }
}